// index.js
const {request} = require('../../utils/util.js')
Component({
  data: {
    title:"提交临时作业",
    searchKeyword: '',      // 搜索关键词
    showDropdown: false,    // 控制下拉显隐
    filteredOptions: [],    // 筛选后的数据
    allOptions: [],         // 全部数据（本地）
    loading: false,         // 远程加载状态
    timer: null,             // 防抖定时器
    selectd:"",
    fileList: [],
    autosize: {
      maxHeight: 120,
      minHeight: 20,
    },
    remark:"",
    file:""
  },
  methods: {
    onLoad: function () {
      this.loadLocalData()
    },
    // 加载本地初始数据
    loadLocalData() {
      const localData = [
      ]
      this.setData({ allOptions: localData,filteredOptions: localData })
    },

    // 输入处理（带防抖）
    handleSearch(e) {
      console.log('输入1111111:')
      clearTimeout(this.data.timer)
      const keyword = e.detail.value.trim()

      this.setData({
        searchKeyword: keyword,
        loading: true,
        showDropdown: true
      })
      console.log('输入:', keyword)
      // 防抖处理（300ms）
      this.data.timer = setTimeout(() => {
        if (keyword.length > 0) {
          console.log('输入1:', keyword)
          this.remoteSearch(keyword)  // 远程搜索
        } else {
          this.localSearch()          // 本地搜索
        }
      }, 300)
    },

    // 本地筛选
    localSearch() {
      const filtered = this.data.allOptions.filter(item =>
          item.label.includes(this.data.searchKeyword)
      )
      this.setData({
        filteredOptions: filtered,
        loading: false
      })
    },

    // 远程搜索（示例）
    remoteSearch(keyword) {

      request('GET', 'api.TempJob/getClNums', {
        num:keyword
      }).then(res => {
        this.setData({
          filteredOptions: res.data || [],
          loading: false
        })


      }).catch(err => {
        console.error('Error:', err);
      });

    },

    // 选择项
    handleSelect(e) {
      const value = e.currentTarget.dataset.value
     // const selected = this.data.filteredOptions.find(item => item.value === value)
      console.log('选中:', value)
      this.setData({ showDropdown: false,searchKeyword: value})
    },

    // 切换下拉
    toggleDropdown() {
      this.setData({ showDropdown: !this.data.showDropdown })
    },

    // 阻止滚动穿透
    preventScroll() {},
    handleAdd(e) {
      const { fileList } = this.data;
      const { files } = e.detail;

      // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
      // this.setData({
      //   fileList: [...fileList, ...files], // 此时设置了 fileList 之后才会展示选择的图片
      // });

      // 方法2：每次选择图片都上传，展示每次上传图片的进度
       files.forEach(file => this.onUpload(file))
    },
    onUpload(file) {
      const { fileList } = this.data;

      this.setData({
        fileList: [...fileList, { ...file, status: 'loading' }],
      });
      const { length } = fileList;

      const task = wx.uploadFile({
        url: 'https://ymy138.cn/base/api.Upload/file', // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        success: (res) => {
          console.log("uploadFile",res)
          let data = JSON.parse(res.data);
          console.log(data)
          if(data.code==1){
            this.setData({
              [`fileList[${length}].status`]: 'done',
              file:data.data.url
            });
          }

        },
      });
      task.onProgressUpdate((res) => {
        this.setData({
          [`fileList[${length}].percent`]: res.progress,
        });
      });
    },
    handleRemove(e) {
      const { index } = e.detail;
      const { fileList } = this.data;

      fileList.splice(index, 1);
      this.setData({
        fileList,
        file:""
      });
    },
    onChange(e) {
      console.log('lineCount: ', e.detail);
      this.setData({
        remark:e.detail.value
      })
    },
    add(){
      let that = this;
      request('POST', 'api.TempJob/savaData', {
        car_number: that.data.searchKeyword,
        remark:that.data.remark,
        img:that.data.file,
      }).then(res => {
        console.log("savaData",res)
        if(res.code==1){
          wx.redirectTo({
            url: '/pages/temp_job/temp_job',
          })
        }else{
          wx.showToast({
            title: res.info,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }



  },
})
